# -*- coding: UTF-8 -*-
# import mysql.connector as db
import client.tWeibo, json
import time, re
import mysql.connector as db

def loadWeiQun(wb):
	# 下载微群
	weiquns = wb.mywqs()
	if weiquns is None:
		print("没有获取到微群信息！")
		return []
	print(weiquns)
	return weiquns
def checkMyWeiboExist(wb, qunid):
	ptn = '<div class="userPic"><a href="%s" title="[^"]+"><img src="http://t3.qlogo.cn/mbloghead/[^/]+/50"/></a></div>' % wb.homeUrl
	response = wb.get('http://qun.t.qq.com/' + qunid)
	responseContent = response.data.decode('utf-8')
	group = re.search(ptn, responseContent)
	if group is None:
		return True
	return False
	
def publishWeiQunWeibo(wb, content, qid, picURL):
	pic = json.loads(wb.uploadextpic(picURL))
	try:
		qpic_url = pic['info']['image']
	except KeyError as ke:
		return False
	return json.loads(wb.publishQun(qid, content, qpic_url, '1'))
def main():
	connect = db.connect(user='root', db='collection', password='', host="127.0.0.1")
	cursor = connect.cursor()
	cursor.execute("SET SQL_MODE = 'TRADITIONAL'")
	uin = 'QQ号'
	passwd = '密码'
	wb = client.tWeibo.tWeibo(uin, passwd)
	wb.login()
	total = 0
	weiquns = []
	while True:
		sqlSelectPics = "SELECT `id`, `gid`, `source`,`add_intro`,`title`,`qpic_url` FROM `xemh` WHERE `gid`<>60850 AND `qpic_url`='' ORDER BY `gid` DESC, `id` DESC LIMIT 12"
		cursor.execute(sqlSelectPics)
		for (wid, gid, source, add_intro, title, qpic_url) in cursor.fetchall():
			while True:
				if len(weiquns) == 0:
					weiquns = loadWeiQun(wb)
					if len(weiquns) == 0:
						import sys
						sys.exit()
				weiqun = weiquns.pop()
				if not checkMyWeiboExist(wb,weiqun['qid']):
					time.sleep(30)
					continue
				result = publishWeiQunWeibo(wb, '#关注我#' + add_intro + '/给力 /走你http://url.cn/9QH7Eu', weiqun['qid'],source)
				break
			total+=1
			try:
				print("%d\t%s\t%s" % (total, weiqun['title'], result['msg']))
			except Exception as e:
				print(result)
				print(e)
			# print(json.dumps(result, sort_keys=True, indent=4))
			try:
				if result['result'] == 0:
					q_weibo_id = result['info']['talk'][0]['id']
					qpic_url = ', '.join(result['info']['talk'][0]['image'])
					cursor.execute("UPDATE `xemh` SET `qpic_url`='%s',`q_weibo_id`='%s' WHERE `id`=%d LIMIT 1" % (qpic_url, q_weibo_id, wid))
					connect.commit()
			except Exception as e:
				print(result)
				print(e)
			print('暂停5分钟.......')
			time.sleep(300)
	cursor.close()
	connect.close()
	
if __name__ == '__main__':
	main()
